frappe.ui.form.on("Material Request", {
    refresh(frm) {
        if (!frm.doc) return;

        // 仅提交状态显示操作按钮
        const is_submitted = frm.doc.docstatus === 1;
        const is_completed = frm.doc.status === "Completed";
        const is_cancelled = frm.doc.status === "Cancelled";

        if (is_submitted && !is_completed) {
            // 同步到 WDT（入库单）
            frm.add_custom_button(__("Sync to WDT"), () => {
                const name = frm.doc.name;
                if (!name) {
                    frappe.msgprint(__("错误：物料申请单名称不存在"));
                    return;
                }
                frappe.confirm(
                    __("Sync Material Request '{0}' to WDT?", [name]),
                    function () {
                        frappe.call({
                            method: "upsystem.upsystem.api.sync_material_request_to_wdt",
                            args: { material_request_name: name },
                            freeze: true,
                            freeze_message: __("正在同步到WDT…"),
                            callback(r) {
                                if (r.message && r.message.success) {
                                    frappe.show_alert({ message: __("Material Request synced to WDT"), indicator: "green" });
                                    frm.reload_doc();
                                } else {
                                    const errorMsg = (r.message && r.message.message) || "Unknown error";
                                    frappe.msgprint({ title: __("Sync Failed"), message: __("Material Request sync failed: {0}", [errorMsg]), indicator: "red" });
                                }
                            },
                            error(err) {
                                frappe.msgprint({ title: __("Sync Failed"), message: err?.message || __("调用接口失败，请稍后重试。"), indicator: "red" });
                            },
                        });
                    }
                );
            }, __("WDT"));
        }

        if (is_submitted && !is_completed && !is_cancelled) {
            // 取消在 WDT 的对应入库单
            frm.add_custom_button(__("Cancel in WDT"), () => {
                const name = frm.doc.name;
                if (!name) {
                    frappe.msgprint(__("错误：物料申请单名称不存在"));
                    return;
                }
                const d = new frappe.ui.Dialog({
                    title: __("取消物料申请单"),
                    fields: [
                        { fieldtype: "Data", fieldname: "cancel_reason", label: __("取消原因"), reqd: 1, placeholder: "请输入取消原因..." },
                    ],
                    primary_action_label: __("确认取消"),
                    primary_action(values) {
                        d.hide();
                        const currentUser = frappe.user.name;
                        const currentDateTime = frappe.datetime.now_datetime();
                        const fullCancelReason = `${values.cancel_reason} | 取消人: ${currentUser} | 取消时间: ${currentDateTime}`;
                        frappe.call({
                            method: "upsystem.upsystem.api.cancel_material_request_in_wdt",
                            args: { material_request_name: name, cancel_reason: fullCancelReason },
                            freeze: true,
                            freeze_message: __("正在取消…"),
                            callback(r) {
                                let msg = "";
                                if (r.message && r.message.success) {
                                    msg = __("物料申请单取消成功！");
                                    frappe.show_alert({ message: msg, indicator: "green" });
                                    frm.reload_doc();
                                } else {
                                    msg = __("物料申请单取消失败: {0}", [r.message?.message || "未知错误"]);
                                    frappe.msgprint({ title: __("取消失败"), message: msg, indicator: "red" });
                                }
                            },
                            error(err) {
                                frappe.msgprint({ title: __("取消失败"), message: err?.message || __("调用接口失败，请稍后重试。"), indicator: "red" });
                            },
                        });
                    },
                });
                d.show();
            }, __("WDT"));
        }
    },
});
